import java.awt.FontFormatException;
import java.io.File;
import java.io.IOException;
import java.util.Observable;

import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;
import org.eclipse.swt.dnd.DropTargetListener;
import org.eclipse.swt.dnd.FileTransfer;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Display;

public class FontDropListener extends Observable implements DropTargetListener {
    public void dragEnter(DropTargetEvent event) {
        if (event.detail == DND.DROP_DEFAULT) {
            if ((event.operations & DND.DROP_COPY) != 0) {
                event.detail = DND.DROP_COPY;
            } else {
                event.detail = DND.DROP_NONE;
            }
        }

        for (int i = 0; i < event.dataTypes.length; ++i) {
            if (FileTransfer.getInstance()
                    .isSupportedType(event.dataTypes[i])) {
                event.currentDataType = event.dataTypes[i];

                // Files should only be copied
                if (event.detail != DND.DROP_COPY) {
                    event.detail = DND.DROP_NONE;
                }

                break;
            }
        }
    }

    public void dragLeave(DropTargetEvent event) {
    }

    public void dragOperationChanged(DropTargetEvent event) {
    }

    public void dragOver(DropTargetEvent event) {
    }

    public void drop(DropTargetEvent event) {
        if (FileTransfer.getInstance().isSupportedType(event.currentDataType)) {
            String[] files = (String[]) event.data;

            for (String file : files) {
                if (Display.getCurrent().loadFont(file)) {
                    try {
                        java.awt.Font awtFont = java.awt.Font.createFont(
                            java.awt.Font.PLAIN, new File(file));
                        String fontName = awtFont.getFontName();
                        FontData[] fontList = Display.getCurrent()
                                .getFontList(fontName, true);

                        for (FontData fontData : fontList) {
                            setChanged();
                            notifyObservers(new FontItem(fontData, false, file));
                        }
                    } catch (FontFormatException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void dropAccept(DropTargetEvent event) {
    }
}